﻿<%@ WebHandler Language="C#" Class="IncomeSummaryPersonal" %>

using System;
using System.Web;
using System.Text;
using Chenxin.Lib.Utility;

public class IncomeSummaryPersonal : AjaxHandlerBase
{
    public IncomeSummaryPersonal()
    {
        //导出
        htTypePermit.Add("export", Constants.Permit_IncomeSummaryPersonal_Export);
        htTypePermit.Add("exportall", Constants.Permit_IncomeSummaryPersonal_Export);
    }
    override public void RequestProcess(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";

            string strOp = context.Request["op"];
            string strRet = string.Empty;
            switch (strOp.ToLower())
            {
                case "getlist":
                    GetList(context);
                    break;
                case "getdtailslist":
                    GetDetailsList(context);
                    break;
                case "exportall":
                    ExportAll(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Chenxin.Lib.Utility.Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    //获取打印全部
    private void ExportAll(HttpContext context)
    {
        //子查询欲选择字段列表
        string TableFieldList = "UserId,UserCode,UserName,CityId,CityName,CompanyId,CompanyName,b.DepartId,b.DepartName,dbo.FN_GetBussinessByDepartID(b.DepartId) as Business,sum(ApportionPay*InOrOut) as Income";
        //所要查询的表名
        string TableName = "dbo.v_Contract_FinanceDetailInfo as a left join Chenxin_Main.dbo.Hr_UserInfo as b on a.PointEmpId=b.UserId";
        //排序
        string strOrderField = " DepartId desc";


        string _strSql = (GetWhere(context));
        string groupStr = " UserId,UserCode,UserName,CityId,CityName,CompanyId,CompanyName,b.DepartId,b.DepartName ";

        if (!string.IsNullOrEmpty(context.Request["sort"]))
        {
            strOrderField = context.Request["sort"];
        }
        else
        {
            strOrderField = " DepartId desc";
        }

        string strSql = "select " + TableFieldList + " from " + TableName + " where " + _strSql + " group by " + groupStr + "order by " + strOrderField;

        System.Data.DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);

        string strHTML = "";
        
        strHTML = GetHtml(ds.Tables[0]);

        ExportByServce(context, strHTML);
    }
    
    //获取打印全部HTML
    private string GetHtml(System.Data.DataTable dt)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<table class=\"tabsorternew table_archive\"><tr>");
        sb.Append("<th style=\"width:120px;\">员工编号</th>");
        sb.Append("<th style=\"width:120px;\">员工姓名</th>");
        sb.Append("<th style=\"width:130px;\">所在商圈</th>");
        sb.Append("<th style=\"width:120px;\">所在门店</th>");
        sb.Append("<th style=\"width:120px;\">个人实收</th></tr>");

        double count = 0.0;            //点数
        
        foreach (System.Data.DataRow dr in dt.Rows)
        {
            sb.Append("<tr>");
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"UserCode",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"UserName",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"Business",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"DepartName",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"Income",""));
            sb.Append("</tr>");

            count += string.IsNullOrEmpty(dr["Income"].ToString()) ? 0 : double.Parse(dr["Income"].ToString());
        }
        sb.AppendFormat("<tr><td>总合计</td><td></td><td></td><td></td><td>{0}</td></tr></table>", count);
        
        
        return sb.ToString();
    }

    private void GetDetailsList(HttpContext context)
    {
        int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
        //页显示行数
        int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
        //欲选择字段列表 
        string FieldList = "*,Results,Business";
        //子查询欲选择字段列表
        string TableFieldList = "*,(RealCommisionFinal-ConsultingFinal) as Results,dbo.FN_GetBussinessByDepartID(PointDepartId) as Business";
        //所要查询的表名
        string TableName = "v_Contract_FinanceDetailInfo b";
        //排序
        string strOrderField = " PointDepartId desc";

        string _strSql = GetWhereForDetail(context);
        
        
        if (!string.IsNullOrEmpty(context.Request["sort"]))
        {
            strOrderField =context.Request["sort"];
        }
        else
        {
            strOrderField =" PointDepartId";
        }

        System.Data.DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strPageIndex, strPageSize, strOrderField, TableName, _strSql, FieldList, TableFieldList,true);

        context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[1].Rows[0][0], Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));

            
    }

    private string GetWhereForDetail(HttpContext context)
    {
        StringBuilder _strWhere = new StringBuilder();
        _strWhere.Append(" (1=1) ");
        //月份
        if (!string.IsNullOrEmpty(context.Request["ActualDate"]))
        {
            string[] list = context.Request["ActualDate"].Split('-');
            _strWhere.AppendFormat(" and PayArchYear='{0}' and PayArchMonth='{1}' ", list[0], list[1].TrimStart('0'));
        }
        //交易类型
        if (!string.IsNullOrEmpty(context.Request["BusinessType"]) && context.Request["BusinessType"] != "50")
        {
            _strWhere.AppendFormat(" and BusinessType={0} ", context.Request["BusinessType"]);
        }
        //首付款开始时间
        if (!string.IsNullOrEmpty(context.Request["StartTime"]))
        {
            _strWhere.AppendFormat(" and PayDate>='{0}' ", context.Request["StartTime"]);
        }
        //首付款结束时间
        if (!string.IsNullOrEmpty(context.Request["EndTime"]))
        {
            _strWhere.AppendFormat(" and PayDate<='{0}' ", context.Request["EndTime"]);
        }
        //人
        if (!string.IsNullOrEmpty(context.Request["empid"]))
        {
            _strWhere.AppendFormat(" and pointempid='{0}'", context.Request["empid"]);
        }
        return _strWhere.ToString();
    }


    private void GetList(HttpContext context)
    {
        int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
        //页显示行数
        int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
        //欲选择字段列表 
        string FieldList = "UserId,UserCode,UserName,CityId,CityName,CompanyId,CompanyName,DepartId,DepartName,Business,Income";
        //子查询欲选择字段列表
        string TableFieldList = "UserId,UserCode,UserName,CityId,CityName,CompanyId,CompanyName,b.DepartId,b.DepartName,dbo.FN_GetBussinessByDepartID(b.DepartId) as Business,sum(ApportionPay*InOrOut) as Income";
        //所要查询的表名
        string TableName = "dbo.v_Contract_FinanceDetailInfo as a left join Chenxin_Main.dbo.Hr_UserInfo as b on a.PointEmpId=b.UserId";
        //排序
        string strOrderField = " DepartId desc";
        
        
        string _strSql = (GetWhere(context));
        string groupStr = " UserId,UserCode,UserName,CityId,CityName,CompanyId,CompanyName,b.DepartId,b.DepartName ";
        
        if (!string.IsNullOrEmpty(context.Request["sort"]))
        {
            strOrderField=context.Request["sort"];
        }
        else
        {
            strOrderField =" DepartId desc";
        }

        System.Data.DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetGroupList(strPageIndex, strPageSize, strOrderField, TableName, _strSql.ToString(),groupStr, FieldList,TableFieldList,true);

        //*************获取总合计数*****************
        string strSql = "select sum(ApportionPay*InOrOut) as Income from " + TableName + " where " + _strSql;
        System.Data.DataSet ds_count = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);
        System.Data.DataRow dr = ds.Tables[0].NewRow();
        dr["UserCode"] = "总合计";
        dr["Income"] = ds_count.Tables[0].Rows[0]["Income"];
        ds.Tables[0].Rows.Add(dr);
        //*****************************************
        
        context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[1].Rows[0][0], Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));

    }

    /// <summary>
    /// 查询条件
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetWhere(HttpContext context)
    {
        StringBuilder _strWhere = new StringBuilder();

        if (CurrentUserInfo.ContainsPermit(Constants.Permit_IncomePersonal_Search_All))
        {
            _strWhere.Append(" (1=1) ");
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_IncomePersonal_Search_City))
        {
            _strWhere.AppendFormat(" (b.DepartId in (Select DepartId from v_Hr_DepartmentInfo WHERE cityid='{0}')) ", CurrentUserInfo.CityId.ToString());
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_IncomePersonal_Search_Company))
        {
            _strWhere.AppendFormat(" (b.DepartId in (select DepartId from v_Hr_DepartmentInfo WHERE companyid='{0}')) ", CurrentUserInfo.CompanyId.ToString());
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_IncomePersonal_Search_Depart))
        {
            _strWhere.Append(" (EXISTS(");
            _strWhere.AppendFormat("Select 1 from t_Business_EmpSetting M WHERE b.DepartId=M.DepartId And M.Userid= '{0}' and SearchIncomePersonal=1", CurrentUserInfo.UserId.ToString());
            _strWhere.Append(")) ");
        }
        else
            _strWhere.AppendFormat(" (pointempid = '{0}') ", CurrentUserInfo.UserId);
        
        //4级
        Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
        Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
        Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
        Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);

        if (departs != Guid.Empty)
        {
            _strWhere.AppendFormat(" and b.DepartId = '{0}'", departs);
        }
        else if (businessdistrict != Guid.Empty)
        {
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
            string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
            if (!cs.Hit)
            {
                item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
            }

            if (item == null)
            {
                context.Response.Write(retExecResult(Chenxin.Lib.Utility.Constants.ExecResult.Error, "获取商圈或分类数据丢失", ""));
            }
            _strWhere.AppendFormat(" and (b.DepartId in (Select DepartId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
        }
        else if (company != Guid.Empty)
        {
            _strWhere.AppendFormat(" and (b.DepartId in (select DepartId from v_Hr_DepartmentInfo WHERE companyid='{0}')) ", company);
        }
        else if (city != Guid.Empty)
        {
            _strWhere.AppendFormat(" and (b.DepartId in (Select DepartId from v_Hr_DepartmentInfo WHERE cityid='{0}')) ", city);
        }


        //月份
        if (!string.IsNullOrEmpty(context.Request["ActualDate"]))
        {
            string[] list = context.Request["ActualDate"].Split('-');
            _strWhere.AppendFormat(" and PayArchYear='{0}' and PayArchMonth='{1}' ", list[0], list[1].TrimStart('0'));
        }


        //交易类型
        if (!string.IsNullOrEmpty(context.Request["BusinessType"]) && context.Request["BusinessType"] != "50")
        {
            _strWhere.AppendFormat(" and BusinessType={0} ", context.Request["BusinessType"]);
        }



        //首付款开始时间
        if (!string.IsNullOrEmpty(context.Request["StartTime"]))
        {
            _strWhere.AppendFormat(" and PayDate>='{0}' ", context.Request["StartTime"]);
        }



        //首付款结束时间
        if (!string.IsNullOrEmpty(context.Request["EndTime"]))
        {
            _strWhere.AppendFormat(" and PayDate<='{0}' ", context.Request["EndTime"]);
        }

        if (!string.IsNullOrEmpty(context.Request["Keyword"]))
        {
            _strWhere.AppendFormat(" and (HouseAddress like '%{0}%' or ContractCode like '%{0}%' or UserCode like '%{0}%')", context.Request["Keyword"]);
        }

        //人
        if (!string.IsNullOrEmpty(context.Request["empid"]))
        {
            _strWhere.AppendFormat(" and pointempid='{0}'", context.Request["empid"]);
        }
        return _strWhere.ToString();
    }

}